package com.voodoo.lib_frame.base;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.voodoo.lib_frame.R;
import com.voodoo.lib_frame.toast.Toast;

import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Author: voodoo
 * CreateDate: 2021/05/16
 * Description: 所有Fragment的基类
 */
public abstract class BaseFragment extends Fragment {

    private Context context;
    private Unbinder unbinder;
    private ProgressDialog progressDialog;

    /***
     * Fragment与Activity绑定完成的时候执行的生命周期
     * @param context 绑定的Activity的Context
     */
    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        this.context = context;
    }

    /**
     * 获取当前Fragment绑定的Context
     *
     * @return Context
     */
    protected Context getFragmentContext() {
        return this.context;
    }

    /**
     * 初始化创建Fragment生命周期
     */
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.activity_base, container, false);
        rootView.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT));
        FrameLayout content = rootView.findViewById(R.id.baseActivity_content_flayout);
        View view = inflater.inflate(getLayoutResId(), null);
        content.addView(view);

        unbinder = ButterKnife.bind(this, view);
        initViews();
        initData();

        return rootView;
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) { // 隐藏的情况下直接移除弹窗
            removeProgressDialog();
        }
    }

    /**
     * 设置加载的布局文件
     *
     * @return 加载的资源文件ID
     */
    protected abstract int getLayoutResId();

    /**
     * 初始化View，设置显隐或初始黄台
     */
    protected abstract void initViews();

    /**
     * 初始化界面的数据
     */
    protected abstract void initData();

    // ==================================================================================== 界面跳转

    /**
     * 跳转界面
     *
     * @param clazz  目标界面
     * @param bundle 携带的参数，若无参数可传，则直接放置null即可
     */
    protected void startActivity(Class<?> clazz, Bundle bundle) {
        Intent intent = new Intent(getFragmentContext(), clazz);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
    }

    /**
     * 带返回数据的跳转，自行实现 {@link #onActivityResult(int, int, Intent)}
     *
     * @param clazz       目标Activity
     * @param bundle      携带的参数，若无参数可传，则直接放置null即可
     * @param requestCode 请求码
     */
    protected void startActivityForResult(Class<?> clazz, Bundle bundle, int requestCode) {
        Intent intent = new Intent(getFragmentContext(), clazz);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivityForResult(intent, requestCode);
    }

    // ======================================================================================= Click

    /**
     * View的点击事件
     *
     * @param view 点击的View
     */
    public void onClick(View view) {
    }

    // ======================================================================================= Toast

    /**
     * 展示 Toast 消息提示
     *
     * @param showMsg 展示信息
     */
    protected void showToast(String showMsg) {
        Toast.showXToast(getActivity(), showMsg);
    }

    /**
     * 展示 Toast 消息提示
     *
     * @param showMsg  展示信息
     * @param duration 展示Toast的时间长短，取值：{@code Toast.LENGTH_SHORT}(2s)、{@code Toast.LENGTH_LONG}(3.5s)
     */
    protected void showToast(String showMsg, int duration) {
        Toast.showXToast(getActivity(), showMsg, duration);
    }

    /**
     * 展示 Toast 消息提示
     *
     * @param showMsg 展示信息
     */
    protected void showRightToast(String showMsg) {
        Toast.showXToast(getActivity(), R.drawable.icon_toast_right, showMsg);
    }

    /**
     * 展示 Toast 消息提示
     *
     * @param showMsg 展示信息
     */
    protected void showErrorToast(String showMsg) {
        Toast.showXToast(getActivity(), R.drawable.icon_toast_error, showMsg);
    }

    /**
     * 展示 ImageToast 消息提示
     *
     * @param drawableResId 展示图片
     * @param showMsg       展示信息
     * @param duration      展示Toast的时间长短，取值：{@code Toast.LENGTH_SHORT}(2s)、{@code Toast.LENGTH_LONG}(3.5s)
     */
    protected void showImageToast(int drawableResId, String showMsg, int duration) {
        Toast.showXToast(getActivity(), drawableResId, showMsg, duration);
    }

    // ============================================================================== ProgressDialog

    /**
     * 展示加载弹窗，创建一个点击Dialog外侧就可取消的弹窗
     *
     * @param loadingStr 展示的信息
     */
    protected void showProgressDialog(String loadingStr) {
        showProgressDialog(loadingStr, true, true);
    }

    /**
     * 展示加载弹窗，创建一个可取消的弹窗
     * <P>用于在点击外侧不可消失但是点击返回键可消失的场景下，这种场景需要将isOutsideCanceled设置为False即可
     *
     * @param loadingStr        提示语
     * @param isOutsideCanceled 点击弹窗外侧是否可关闭Dialog
     */
    protected void showProgressDialog(String loadingStr, boolean isOutsideCanceled) {
        // 点击弹窗外侧是否可以消失
        showProgressDialog(loadingStr, true, isOutsideCanceled);
    }

    /**
     * 展示加载框
     *
     * @param loadingStr        加载框中提示内容
     * @param isCancel          弹窗是否可关闭（总开关），如果为false弹窗无法关闭，返回和点击Dialog外侧都无法取消
     * @param isOutsideCanceled 点击弹窗外是否可关闭弹窗，isCancel优先，如果isCancel为true，此参数才有效
     */
    protected void showProgressDialog(String loadingStr, boolean isCancel, boolean isOutsideCanceled) {

        if (!isHidden()) {
            // 先将Dialog移除
            removeProgressDialog();

            // 创建Dialog弹窗
            progressDialog = new ProgressDialog(getFragmentContext(), R.style.loading_dialog);
            progressDialog.setIndeterminate(true);
            progressDialog.setCancelable(isCancel);
            progressDialog.setCanceledOnTouchOutside(isOutsideCanceled);
            progressDialog.show();

            // 设置Dialog展示的内容View
            View views = LayoutInflater.from(getFragmentContext()).inflate(R.layout.view_loading_dialog, null);
            TextView loading_tv_content = views.findViewById(R.id.loading_tv_content);
            loading_tv_content.setText(loadingStr);
            progressDialog.setContentView(views);

        }

    }

    /**
     * 移除加载框
     */
    protected void removeProgressDialog() {
        if (progressDialog != null) {
            if (progressDialog.isShowing() && !isHidden()) {
                progressDialog.dismiss();
                progressDialog = null;
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // 销毁界面的时候解绑
        unbinder.unbind();
    }

}
